/*
 * @depends component.js, Portal.js
 */
QFinance.component.OverviewPanel = Ext.extend( QFinance.ui.Portal, {
    region: 'center',
    portletsToRemove: [],
	
    // Localization
    addPortletText: 'Add portlet',
    selectPortletText: 'Select portlet',
    accountsBalanceText: 'Accounts balance',
    topAmountText: 'Top amount',
    accountsBalanceHistory: 'Accounts balance history',
    columnText: 'Column',
    addColumnText: 'Add',
    removeColumnText: 'Remove',
    saveText: 'Save',
	
    constructor: function(cfg) {
        Ext.apply(this, cfg);		
		
        QFinance.component.OverviewPanel.superclass.constructor.call(this);
    },
	
    initComponent: function() {		
        this.initButtonBar();        
        Ext.apply(this, {			
            items: []
        });
        QFinance.component.OverviewPanel.superclass.initComponent.call(this);
    },	
	
    initButtonBar: function() {
        this.tbar = {
            items: [{
                text: this.addPortletText,
                iconCls: 'puzzle--plus',
                scope: this,
                handler: function() {
                    var portletSelectWindow = new QFinance.ui.SelectWindow({
                        title: this.selectPortletText,
                        options: [
                        ['AccountsBalancePortlet', this.accountsBalanceText],
                        ['TopAmountPortlet', this.topAmountText],
                        ['AccountsBalanceHistoryPortlet', this.accountsBalanceHistory]
                        ],
                        renderTo: this.getEl(),
                        modal: true,
                        scope: this,
                        handler: function( className ) {							
                            var portlet = QFinance.portlet.PortletFactory.getPortletInstanceByClass( className );
                            if (portlet) {
                                portlet.configure(this, function() {
                                    this.addPortlet( portlet );
                                    this.doLayout();
                                }, this);
                            }
                        }
                    });
                    portletSelectWindow.show();
                }
            },{
                text: this.columnText,
                iconCls: 'layout',
                menu: {
                    xtype: 'menu',
                    style: {
                        overflow: 'visible'
                    },
                    items: [{
                        text: this.addColumnText,
                        iconCls: 'layout-split',
                        scope: this,
                        handler: function() {
                            this.addColumn();
                            this.doLayout();
                        }
                    },{
                        text: this.removeColumnText,
                        iconCls: 'layout-join',
                        scope: this,
                        handler: function() {
                            this.removeColumn();
                            this.doLayout();
                        }
                    }]
                }					
            }]			
        };		
    },
	
    initStatusBar: function(toolbar) {
        toolbar.insert(0, new Ext.Button({
            text: this.saveText,
            formBind: true,
            scope: this,
            iconCls: 'fugue-disk-black',
            handler: function() {
                this.doSave();	 
            }
        }));
    },
	
    addPortlet: function( portlet, lin, col ) {		
        this.checkCol(col == null ? 1 : col);
        if (lin == null)
            this.items.itemAt(0).add(portlet);
        else 
            this.items.itemAt(col-1).insert(lin-1, portlet);	
    },
	
    addColumn: function() {							
        this.add(new Ext.ux.PortalColumn({
            columnWidth: 0,
            style: 'padding: 10px'
        }));
        this.resizeColumns();
    },
	
    removeColumn: function() {
        if (this.items.getCount() > 1) {
            var lastColumn = this.items.last();
            var targetColumn = this.items.itemAt(this.items.getCount()-2);
            lastColumn.items.each(function(item) {
                targetColumn.add(item);
            });
            this.remove(lastColumn);
            this.resizeColumns();
        }
    },
	
    resizeColumns: function() {
        var columns = this.items.getCount();
        this.items.each(function(item) {
            item.columnWidth = (100/columns)/100;
        });		
    },
	
    checkCol: function(col) {		
        var diff = col - this.items.getCount();
        for (var i = 1; i <= diff; i++ ) {
            this.addColumn();
        }
    },
	
    loadPortlets: function() {		
        var loadPortletsID = this.getProcessStatusManager().start([this]);
        QFinance.Remoting.OverviewPanelAction.getPortlets(function(result, event) {
            var message = '';
            var where = '';
            var failure = false;
			
            if (result) {
                if (result.success) {					
                    for (var i = 0; i < result.data.length; i++) {
                        var portlet = QFinance.portlet.PortletFactory.getPortletInstanceByClass( result.data[i].className );
                        if (portlet) {
                            portlet.internalID = result.data[i].id;
                            portlet.configuration = result.data[i].configuration && result.data[i].configuration;	
                            this.addPortlet(portlet, result.data[i].lin, result.data[i].col );
                            this.doLayout();
                            portlet.loadData();
                        }
                    }
                    this.getProcessStatusManager().success(loadPortletsID);
                } else {
                    failure = true;						
                    message = result.message;
                    if (result.type == 'exception')
                        where = result.where;
                }            
            } else {
                failure = true;
                message = event.message;
            }
			
            if (failure) {
                this.getProcessStatusManager().error(loadPortletsID, message);                
                QFinance.service.DeveloperService.log('Direct call failure: ' + message + ' where\n' + where);				
            }
			
        }, this);		
    },
	
    doSave: function() {
        var doSaveID = this.getProcessStatusManager().start([this]);
        var portlets = [];
		
        for (var col = 0; col < this.items.getCount(); col++) {
            for (var lin = 0; lin < this.items.itemAt(col).items.getCount(); lin++) {
                portlets.push( {
                    internalID: this.items.itemAt(col).items.itemAt(lin).internalID,
                    className: this.items.itemAt(col).items.itemAt(lin).className,
                    configuration: this.items.itemAt(col).items.itemAt(lin).configuration,
                    col: col + 1,
                    lin: lin + 1
                });
            }
        }
        QFinance.Remoting.OverviewPanelAction.savePortlets(portlets, this.portletsToRemove, function(result, event) {
            var message = '';
            var where = '';
            var failure = false;
			
            if (result) {
                if (result.success) {
                    this.getProcessStatusManager().success(doSaveID);                    
                } else {
                    failure = true;						
                    message = result.message;
                    if (result.type == 'exception')
                        where = result.where;
                }            
            } else {
                failure = true;
                message = event.message;
            }
			
            if (failure) {
                this.getProcessStatusManager().success(doSaveID, message);
                QFinance.service.DeveloperService.log('Direct call failure: ' + message + ' where\n' + where);
            }
			
            this.portletsToRemove = [];
        }, this);
    },
	
    markToRemove: function(portlet) {		
        this.portletsToRemove.push(portlet.internalID);
    }
});
Ext.reg('QFinance.component.OverviewPanel', QFinance.component.OverviewPanel);